package com.example.primarycalculator2;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ProblemAdapter extends ArrayAdapter<Problem> {
    private int resourceId;
    HashMap<Integer,String> hashMap=new HashMap<>();
    private Context context;
    private List<Problem> problems;

//    如果要更改源数据，需要在这一步进行绑定，super不是绑定
    public ProblemAdapter(@NonNull Context context, int resource, @NonNull List<Problem> objects) {
        super(context, resource, objects);
        this.problems=objects;
        this.context=context;
        this.resourceId=resource;
    }



    @Override
    public int getCount() {
        return super.getCount();
    }


    public ArrayList<Problem> getarrayList(ArrayList<Problem> problems){
        int size=problems.size();
        for (int i=0;i<size;i++){
            if(hashMap.get(i)!=null){
                problems.get(i).setAnswer(hashMap.get(i));
            }
        }
        return problems;
    }


    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Problem problem=getItem(position);
        View view= LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
        TextView problemContent=view.findViewById(R.id.problem);
        EditText problemAnswer=view.findViewById(R.id.answer);
        problemContent.setText(problem.getContent());
        problemAnswer.setText("");

        problemAnswer.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                problems.get(position).setAnswer(s.toString());
            }
            @Override
            public void afterTextChanged(Editable s) {
                hashMap.put(position,s.toString());
            }
        });
        if(hashMap.get(position)!=null){
            problemAnswer.setText(hashMap.get(position));
        }
        return view;
    }

}
